﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;

namespace GqqMvcWeb.Models.Database
{
    public class SchoolContext : DbContext
    {
        /// <summary>
        /// 通过这种方式，自定义连接字符串
        /// </summary>
        public SchoolContext()
            //用name=这种方式，规定了app.config中的字符串必须使用SchoolString，否则，就会报错误。
            : base("name=SchoolString")
        {
            // Get the ObjectContext related to this DbContext
            var objectContext = (this as IObjectContextAdapter).ObjectContext;

            // Sets the command timeout for all the commands
            objectContext.CommandTimeout = 120;
            this.Configuration.LazyLoadingEnabled = false;
        }

        public IDbSet<course> Courses { get; set; }
        public IDbSet<department> Departments { get; set; }
        public IDbSet<enrollment> Enrollments { get; set; }
        public IDbSet<instructor> Instructors { get; set; }
        public IDbSet<student> Students { get; set; }
        public IDbSet<officeAssignment> OfficeAssignments { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// ReSharper disable CSharpWarnings::CS0612
//            modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
// ReSharper restore CSharpWarnings::CS0612

//            modelBuilder.Entity<instructor>()
//                .HasOptional(p => p.OfficeAssignment).WithRequired(p => p.Instructor);
//            modelBuilder.Entity<course>()
//                .HasMany(c => c.Instructors).WithMany(i => i.Courses)
//                .Map(t => t.MapLeftKey("CourseID")
//                              .MapRightKey("InstructorID")
//                              .ToTable("CourseInstructor"));
            //A department may or may not have an administrator, 
            //and an administrator is always an instructor. 
            //Therefore the InstructorID property is included as the foreign key to the Instructor entity, 
            //and a question mark is added after the int type designation to mark the property as nullable.
            //The navigation property is named Administrator but holds an Instructor entity:
//            modelBuilder.Entity<department>()
//                .HasOptional(x => x.Administrator);
        }
    }
}